package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.audioserver.TaskAudioConfig;
import com.chinamcloud.collect.AcquisitionManager;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.cloud.ijkplayersdk.untils.Tools;
import com.mediacloud.app.model.adaptor.BaseAdaptor;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.PayTipsUtilsKt;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.RelativeNewsInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.view.AudioBottomPopWin;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 音频直播类
 *
 * @author x
 */
public class AudioVodDetailActivity extends BaseAudioActivity implements OnItemClickListener, DataInvokeCallBack<ArticleListData> {
    private List<String> bitRateUrls = new ArrayList<>();
    private List<String> bitRateTitles = new ArrayList<String>();
    private NewsDetailInvoker newsDetailInvoker;
    private AudioDetailCallBack audioDetailCallBack;
    private AudioStreamLineAdaptor streamLabelAdaptor;
    private AudioBottomPopWin<String> audioBottomPopWin;
    //相关音频
    private AuidoRealtiveAdaptor audioRelativeAdaptor;
    private AudioVodRelativeBottomFragment<ArticleItem> audioRelativePopWin;
    private RelativeNewsInvoker relativeNewsInvoker;

    int playListIndex = -1;
    private boolean isLoop = false;
    private int speedIndex = 1;
    private int bitRateIndex = 0;
    protected List<ArticleItem> audioList = new ArrayList<ArticleItem>();
    long  mTyReportStartTime=0;
    long  mTyReportEndTime=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        programBtn.setVisibility(View.GONE);
        if (isFullScreen()) {
            ViewGroup.LayoutParams layoutParams = collectionBtn.getLayoutParams();
            if (layoutParams instanceof ConstraintLayout.LayoutParams) {
                ConstraintLayout.LayoutParams cl = (ConstraintLayout.LayoutParams) layoutParams;
                cl.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
                cl.horizontalChainStyle = ConstraintLayout.LayoutParams.CHAIN_SPREAD_INSIDE;
                collectionBtn.setLayoutParams(cl);
            }
        }
        TaskAudioConfig config = APSHelper.getTaskConfig("" + articleItem.getId());
        if (config != null) {
            try {
                isLoop = config.getLoop();
                speedIndex = config.getSpeedIndex();
                bitRateIndex = config.getBitRateIndex();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        audioBottomPopWin = new AudioBottomPopWin<>(this);
        audioRelativeAdaptor = new AuidoRealtiveAdaptor(this, audioList);
        audioRelativePopWin = new AudioVodRelativeBottomFragment<ArticleItem>(this);
        audioRelativePopWin.setItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                playListIndex = position;
                if (position > audioList.size() - 1)
                    return;
                ArticleItem item = audioList.get(position);

                if (item == null)
                    return;
                articleItem = item;
                readStatus();
                setArgs();
                customViewLayout();
                getAudioDetail();
            }
        });
        audioBottomPopWin.setItemClickListener(this);
        customViewLayout();
        audioDetailCallBack = new AudioDetailCallBack();
        newsDetailInvoker = new NewsDetailInvoker(audioDetailCallBack);
        relativeNewsInvoker = new RelativeNewsInvoker(this);
        getAudioDetail();
        updatePlayModeDrawable();
        onPageStart();
    }




    @Override
    protected void onPaidAudio(String audio) {
        articleItem.setAudio(audio);
        checkNetAndsendPlayCMD();
    }

    protected void checkNetAndsendPlayCMD() {
        Log.w(TAG, "checkNetAndsendPlayCMD");
        // sendPlayCMD();
        checkNetType();
    }

    @Override
    public void success(ArticleListData result) {
        audioList.clear();
        if (result.state) {
            audioList.addAll(result.articleList);
        }
    }
    @Override
    public void fault(Object data) {

    }

    protected void customViewLayout() {
        next_audioBtn.setVisibility(View.GONE);
        prev_audioBtn.setVisibility(View.GONE);
        //		loopModeBtn.setVisibility(View.GONE);
        next_audioBtn.setClickable(false);
        prev_audioBtn.setClickable(false);
//        programBtn.setClickable(true);
//        programBtn.setVisibility(View.GONE);
        //		totoalLength.setVisibility(View.GONE);
        //		currentPlayPosition.setGravity(Gravity.CENTER);
        currentPlayPosition.setText(Tools.convertTimeFormat(0));
        totoalLength.setText("");
        seekbar.setEnabled(false);
        //		next_audioBtn.setOnClickListener(this);
        //		prev_audioBtn.setOnClickListener(this);
        loopModeBtn.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.loopModeBtn) {
            isLoop = !isLoop;
            updatePlayModeDrawable();
            apsKit.setLoop(isLoop);
        }
    }


    protected void updatePlayModeDrawable() {
        Drawable drawable = null;
        if (isLoop) {
            drawable = isFullScreen() ? tintDrawable(R.drawable.audio_play_order, getPaletteColor()) : getResources().getDrawable(R.drawable.audio_play_order_select);
        } else {
            drawable = isFullScreen() ? tintDrawable(R.drawable.audio_play_order, Color.WHITE) : getResources().getDrawable(R.drawable.audio_play_order);
        }
        loopModeBtn.normalImg = loopModeBtn.pressImg = drawable;
        loopModeBtn.updateEffDrawable();
    }


    class AudioDetailCallBack implements DataInvokeCallBack<ArticleItemReciver> {
        @Override
        public void success(ArticleItemReciver data) {
            if (data.state) {
                if (articleItem != null && articleItem.getFromComponent() != 1)
                    setNewsTitle();
                if (articleItem != null && articleItem.getId() == data.articleItem.getId()) {
                    mTyReportEndTime=mTyReportStartTime=System.currentTimeMillis();
                }
                articleItem = data.articleItem;
                articleItem.setmShowSwitch(showSwitch);
                openLikeBtn = articleItem != null && articleItem.getTagsflag() == 1 && AppFactoryGlobalConfig.getAppServerConfigInfo(AudioVodDetailActivity.this).getOtherFunction() != null && AppFactoryGlobalConfig.getAppServerConfigInfo(AudioVodDetailActivity.this).getOtherFunction().getSupport() > 0;// "1".equals(getResources().getString(R.string.openLikeBtn));
                if (openLikeBtn) {
                    likeBadgeView.setVisibility(View.VISIBLE);
                } else {
                    likeBadgeView.showBadgeText(false);
                    likeBadgeView.setVisibility(View.GONE);
                }
                UserRecommend.addItemKeyWord(articleItem, AudioVodDetailActivity.this);
                loadedImg = false;

                //    badgeView.setText(articleItem.getCommentCount() + "");
                commentsBadgeView.setBadgeText(articleItem.getCommentCount() + "");
                if (articleItem.getCommentCount() > 0) {
                    commentsBadgeView.showBadgeText(true);
                } else {
                    commentsBadgeView.showBadgeText(false);
                    commentsBadgeView.setBadgeTextViewGone();
                }

                if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                    normalPayUtil.showPaidView();
                    optPlayUrl();
                } else {
                    normalPayUtil.judgeShowPayView(articleItem);
                }
                startAddIntegralCounter();
                AddMedalStatistics.addMedalStatistics(AudioVodDetailActivity.this); //勋章统计

                // getComponentData();
            } else {
                ToastUtil.show(AudioVodDetailActivity.this, R.string.noraml_newserror);

            }
            broccoliLayout.setVisibility(View.GONE);
        }

        @Override
        public void fault(Object data) {
            ToastUtil.show(AudioVodDetailActivity.this, R.string.noraml_newserror);
        }
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null){
                    return;
                }
                Addintegral.addintegral(AudioVodDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    protected void optPlayUrl() {

        try {
            JSONObject video = new JSONObject(articleItem.getAudio());
            JSONArray tsAddress = video.optJSONArray("PC");
            cdnEncrypt = video.optString("cdnConfigEncrypt");
            bitRateTitles.clear();
            bitRateUrls.clear();
            for (int i = 0; i < tsAddress.length(); i++) {
                JSONObject line = tsAddress.optJSONObject(i);
                String title = line.optString("title");
                String url = line.optString("url");
                bitRateUrls.add(url);
                bitRateTitles.add(title);
            }

            if (bitRateIndex < bitRateUrls.size()) {
                MusicEntity entity = new MusicEntity(articleItem.getTitle(),bitRateUrls.get(bitRateIndex));
                entity.setAlbum("");
                entity.setSinger("");
                apsKit.setData(entity);
                String title = bitRateTitles.get(bitRateIndex);
                streamLineBtn.setText(title);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(this, R.string.noraml_newserror);
        }
    }

    @Override
    void openProgramList() {
        if (audioRelativeAdaptor.getCount() == 0) {
            ToastUtil.showCustomView(this, R.string.no_releative_audio_resource);
            return;
        }
        audioRelativePopWin.show(mRootView, false);
        if (isFullScreen()) {
            audioRelativePopWin.setListviewBackgroundColor(0x7fffffff);
        }
        audioRelativePopWin.setListAdaptor(audioRelativeAdaptor);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    protected List<View> getPaidViews() {
        List<View> list = new ArrayList<>();
        list.add(seekbar);
        return list;
    }

    @Override
    public void finish() {

        super.finish();
        if (articleItem!=null&&mTyReportStartTime>0) {
            mTyReportEndTime=System.currentTimeMillis();
        }
        if(apsKit.isPlaying()){
            if(apsKit.isTaskPlaying()){
                TaskAudioConfig config = new TaskAudioConfig(isLoop, speedIndex, bitRateIndex);
                APSHelper.saveTaskConfig("" + articleItem.getId(),config);
            }
            sendShowFloaWinMsg();
        }else{
            KillMusicUtils.hideReadNewsWin();
        }
        if (newsDetailInvoker != null)
            newsDetailInvoker.destory();
        newsDetailInvoker = null;
        if (relativeNewsInvoker != null)
            relativeNewsInvoker.destory();
        relativeNewsInvoker = null;
    }

    protected void getAudioDetail() {
        if (isFinish)
            return;
        relativeNewsInvoker.getRelativeVideoList(String.valueOf(articleItem.getId()));
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById("" + articleItem.getId(), navigate_id);
    }


    @Override
    protected void showStreamLine() {
        if (!isFullScreen()) {
            if (streamLabelAdaptor == null) {
                streamLabelAdaptor = new AudioStreamLineAdaptor(this, bitRateTitles);
            }
            audioBottomPopWin.setListAdaptor(streamLabelAdaptor);
            backgroundAlpha(0.5f);
            audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
            audioBottomPopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
            return;
        }

    }

    /**
     * 设置添加屏幕的背景透明度(值越大,透明度越高)
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }


    class AuidoRealtiveAdaptor extends BaseAdaptor<ArticleItem> {

        public AuidoRealtiveAdaptor(Context context, List<ArticleItem> list) {
            super(context, list);
        }

        public AuidoRealtiveAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_audiorealtive_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            PayTipsUtilsKt.payTips(audioLineItem, mContext.getResources().getText(R.string.pay_a_pei), getItem(position), mContext.getResources().getDimensionPixelSize(R.dimen.pay_label_size), mContext.getResources().getDimensionPixelSize(R.dimen.pay_label_bgradius));
            if (position == playListIndex) {
                audioLineItem.setTextColor(getPaletteColor());
            } else
                audioLineItem.setTextColor(Color.BLACK);
            return convertView;
        }

        @Override
        public int getCount() {
            if (mContentListData != null)
                return mContentListData.size();
            return 0;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        bitRateIndex=position;
        String title = bitRateTitles.get(position);
        streamLineBtn.setText(title);
        MusicEntity entity = new MusicEntity( articleItem.getTitle(),bitRateUrls.get(position));
        entity.setAlbum("");
        entity.setSinger("");
        apsKit.setData(entity);
        apsKit.resetSourceAndPlayer();
        apsKit.toggle();
    }


    class AudioStreamLineAdaptor extends BaseAdaptor<String> {

        public AudioStreamLineAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AudioStreamLineAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_vod_audiosource_change_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            audioLineItem.setText(getItem(position));
            ImageView imageViewCheck = Utility.findViewById(convertView, R.id.image_checked);
            if (bitRateIndex ==position) {
                imageViewCheck.setImageResource(R.drawable.image_check);
            } else {
                imageViewCheck.setImageResource(R.drawable.image_uncheck);
            }
            return convertView;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readEnter(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readExit(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin()) {
            getAudioDetail();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}